package com.hema.auction.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.LinkMovementMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.reyun.sdk.TrackingIO;
import com.tencent.connect.UserInfo;
import com.tencent.connect.common.Constants;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.hema.auction.R;
import com.hema.auction.activity.H5Activity;
import com.hema.auction.activity.MainActivity;
import com.hema.auction.base.BaseFragment;
import com.hema.auction.bean.ProfileInfo;
import com.hema.auction.bean.QQInfo;
import com.hema.auction.event.TabIndexEvent;
import com.hema.auction.http.HttpTag;
import com.hema.auction.http.UrlManager;
import com.hema.auction.http.biz.HttpManager;
import com.hema.auction.utils.Constant;
import com.hema.auction.utils.Utils;
import com.hema.auction.utils.manager.ScreenManager;
import com.hema.auction.widget.MyClickable;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * 描述:
 * 作者:john
 */
public class LoginFragment extends BaseFragment {

    @BindView(R.id.et_account)
    EditText etAccount;
    @BindView(R.id.iv_account_del)
    ImageView ivAccountDel;
    @BindView(R.id.et_pwd)
    EditText etPwd;
    @BindView(R.id.iv_eye)
    ImageView ivEye;
    @BindView(R.id.cb_agreement)
    CheckBox cbAgreement;
    @BindView(R.id.tv_agreement)
    TextView tvAgreement;
    @BindView(R.id.tv_login)
    TextView tvLogin;
    @BindView(R.id.tv_wechat)
    TextView tvWechat;
    @BindView(R.id.tv_qq)
    TextView tvQq;
    private IWXAPI api;
    private Tencent tencent;

    @Override
    protected int getLayout() {
        return R.layout.fragment_login;
    }

    @Override
    protected void init() {
        super.init();
        tvAgreement.setText(getClickableSpan());
        tvAgreement.setMovementMethod(LinkMovementMethod.getInstance());
        regoToWx();
        regoToQQ();
        etAccount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (etAccount.getText().toString().trim().length() > 0) {
                    ivAccountDel.setVisibility(View.VISIBLE);
                } else {
                    ivAccountDel.setVisibility(View.GONE);
                }
                if (etAccount.getText().toString().trim().length() > 0 && etPwd.getText().toString().trim().length() > 0) {
                    tvLogin.setEnabled(true);
                    tvLogin.setTextColor(getResources().getColor(R.color.white));
                    tvLogin.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                } else {
                    tvLogin.setEnabled(false);
                    tvLogin.setTextColor(getResources().getColor(R.color.gray99));
                    tvLogin.setBackgroundColor(getResources().getColor(R.color.layout_bg));
                }
            }
        });
        etPwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (etPwd.getText().toString().trim().length() > 0) {
                    ivEye.setVisibility(View.VISIBLE);
                } else {
                    ivEye.setVisibility(View.GONE);
                }
                if (etAccount.getText().toString().trim().length() > 0 && etPwd.getText().toString().trim().length() > 0) {
                    tvLogin.setEnabled(true);
                    tvLogin.setTextColor(getResources().getColor(R.color.white));
                    tvLogin.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                } else {
                    tvLogin.setEnabled(false);
                    tvLogin.setTextColor(getResources().getColor(R.color.gray99));
                    tvLogin.setBackgroundColor(getResources().getColor(R.color.layout_bg));
                }
            }
        });
    }


    private CharSequence getClickableSpan() {
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString(Constant.EXTRA_TITLE, getString(R.string.reg_agreement));
                bundle.putString(Constant.EXTRA_URL, UrlManager.H5_REGISTER_AGREEMENT);
                intentTo(H5Activity.class, bundle);
            }
        };
        SpannableString spanableInfo = new SpannableString(tvAgreement.getText().toString());
        int start = 4;
        int end = 10;
        spanableInfo.setSpan(new MyClickable(getActivity(), listener), start, end, Spanned.SPAN_MARK_MARK);
        return spanableInfo;
    }


    @Override
    public void onResume() {
        super.onResume();
        if (!Utils.isEmpty(Constant.TEMP_CODE)) {
            String wxCode = Constant.TEMP_CODE;
            isAutoDismissDialog = false;
            showProgressDialog(false);
            HttpManager.getInstance(getActivity()).getWXToken(wxCode, this);
            Constant.TEMP_CODE = "";
        }
    }

    @OnClick({R.id.iv_account_del, R.id.iv_eye, R.id.tv_login, R.id.tv_qq, R.id.tv_wechat})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_account_del:
                etAccount.setText("");
                break;
            case R.id.iv_eye:
                if (etPwd.getTransformationMethod() instanceof HideReturnsTransformationMethod) {
                    ivEye.setImageResource(R.drawable.ic_eye_def);
                    etPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                } else {
                    ivEye.setImageResource(R.drawable.ic_eye_sel);
                    etPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                }
                etPwd.setSelection(etPwd.getText().toString().length());
                break;
            case R.id.tv_login:
                if (cbAgreement.isChecked()) {
                    showProgressDialog();
                    HttpManager.getInstance(getActivity()).login(etAccount.getText().toString().trim(), Utils.stringToMD5(etPwd.getText().toString().trim()), this);
                } else {
                    showToastSafe(R.string.please_agree_privacy_agreement);
                }
                break;
            case R.id.tv_qq:
                qqLogin();
                break;
            case R.id.tv_wechat:
                wechatLogin();
                break;
        }
    }


    @Override
    protected void onSuccess(HttpTag httpTag, Call call, JSONObject result) {
        super.onSuccess(httpTag, call, result);
        switch (httpTag) {
            case TAG_LOGIN:
                try {
                    if (result.getInt("errcode") == 0) {
                        spManager.setIsLogin(true);
                        profileInfo = new Gson().fromJson(result.getJSONObject("data").toString(), ProfileInfo.class);
                        TrackingIO.setLoginSuccessBusiness(profileInfo.getId());
                        setAlisa();
                        updateProfile();
                        spManager.setUserId(profileInfo.getId());
                        ScreenManager.getInstance().popAllActivitys(MainActivity.class);
                        EventBus.getDefault().post(new TabIndexEvent(3, profileInfo.isNewUser()));
                        getActivity().finish();
                    }
                    showToastSafe(result);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case TAG_GET_WX_TOKEN:
                try {
                    String token = result.getString("access_token");
                    String openid = result.getString("openid");
                    HttpManager.getInstance(getActivity()).getWXInfo(token, openid, this);
                } catch (JSONException e) {
                    e.printStackTrace();
                    dismissProgressDialog();
                }
                break;
            case TAG_GET_WX_INFO:
                try {
                    HttpManager.getInstance(getActivity()).thirdLogin(result.getString("openid"), "1",
                            result.getString("nickname"),
                            result.getString("headimgurl"), LoginFragment.this);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case TAG_THIRD_LOGIN:
                try {
                    if (result.getInt("errcode") == 0) {
                        spManager.setIsLogin(true);
                        profileInfo = new Gson().fromJson(result.getJSONObject("data").toString(), ProfileInfo.class);

                        setAlisa();
                        updateProfile();
                        spManager.setUserId(profileInfo.getId());
                        if (profileInfo.isNewUser())
                            TrackingIO.setRegisterWithAccountID(profileInfo.getId());
                        else
                            TrackingIO.setLoginSuccessBusiness(profileInfo.getId());
                        EventBus.getDefault().post(new TabIndexEvent(3, profileInfo.isNewUser()));
//                        Bundle bundle = new Bundle();
//                        bundle.putInt(Constant.EXTRA_TAB_INDEX,3);
                        getActivity().finish();
                    }
                    showToastSafe(result);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    @Override
    public void onFailure(HttpTag httpTag, Call call, IOException e) {
        super.onFailure(httpTag, call, e);
        switch (httpTag) {
            case TAG_GET_WX_TOKEN:
                dismissProgressDialog();
                break;
        }
    }

    @Override
    protected void onFinish(HttpTag httpTag) {
        super.onFinish(httpTag);
        switch (httpTag) {
            case TAG_GET_WX_INFO:
                dismissProgressDialog();
                break;
        }
    }

    /**
     * 微信授权登录
     */
    private void regoToWx() {
        api = WXAPIFactory.createWXAPI(getActivity(), Constant.WECHAT_APP_ID, false);
        api.registerApp(Constant.WECHAT_APP_ID);
    }

    /**
     * QQ授权登录
     */
    private void regoToQQ() {
        tencent = Tencent.createInstance(Constant.QQ_APP_ID, getActivity());
    }

    private void wechatLogin() {
        SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "auction_wechat_login";
        api.sendReq(req);
    }

    private void qqLogin() {
//        if (!tencent.isSessionValid()) {
        tencent.login(this, "all", qqLoginListener);
//        } else {
//            tencent.checkLogin(qqLoginListener);
//        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Constants.REQUEST_LOGIN) {
            tencent.handleResultData(data, qqLoginListener);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private IUiListener qqLoginListener = new IUiListener() {
        @Override
        public void onComplete(Object o) {
            JSONObject json = (JSONObject) o;
            QQInfo info = new Gson().fromJson(json.toString(), QQInfo.class);
            tencent.setAccessToken(info.getAccessToken(), String.valueOf(info.getExpiresIn()));
            tencent.setOpenId(info.getOpenid());
            UserInfo userInfo = new UserInfo(getActivity(), tencent.getQQToken());
            userInfo.getUserInfo(userInfoListener);
        }

        @Override
        public void onError(UiError uiError) {

        }

        @Override
        public void onCancel() {

        }
    };

    private IUiListener userInfoListener = new IUiListener() {
        /**
         * {
         "ret": 0,
         "msg": "",
         "is_lost": 0,
         "nickname": "john",
         "gender": "男",
         "province": "江西",
         "city": "赣州",
         "figureurl": "http:\/\/qzapp.qlogo.cn\/qzapp\/1106309780\/B452A5ECB06CAABCAC6BCC54B30F9C60\/30",
         "figureurl_1": "http:\/\/qzapp.qlogo.cn\/qzapp\/1106309780\/B452A5ECB06CAABCAC6BCC54B30F9C60\/50",
         "figureurl_2": "http:\/\/qzapp.qlogo.cn\/qzapp\/1106309780\/B452A5ECB06CAABCAC6BCC54B30F9C60\/100",
         "figureurl_qq_1": "http:\/\/q.qlogo.cn\/qqapp\/1106309780\/B452A5ECB06CAABCAC6BCC54B30F9C60\/40",
         "figureurl_qq_2": "http:\/\/q.qlogo.cn\/qqapp\/1106309780\/B452A5ECB06CAABCAC6BCC54B30F9C60\/100",
         "is_yellow_vip": "0",
         "vip": "0",
         "yellow_vip_level": "0",
         "level": "0",
         "is_yellow_year_vip": "0"
         }
         * @param o
         */
        @Override
        public void onComplete(Object o) {
            try {
                isAutoDismissDialog = false;
                JSONObject result = (JSONObject) o;
                HttpManager.getInstance(getActivity()).thirdLogin(tencent.getOpenId(), "2",
                        result.getString("nickname"),
                        result.getString("figureurl_qq_2"), LoginFragment.this);
                showProgressDialog();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onError(UiError uiError) {

        }

        @Override
        public void onCancel() {

        }
    };

}
